#include "core/editor/find_replace_dialog.h"
#include <QPlainTextEdit>
#include <QLineEdit>
#include <QCheckBox>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>

FindReplaceDialog::FindReplaceDialog(QPlainTextEdit *editor, QWidget *parent)
    : QDialog(parent), editor(editor) {
    setWindowTitle("查找和替换");
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    QHBoxLayout *findLayout = new QHBoxLayout();
    findLayout->addWidget(new QLabel("查找:"));
    findEdit = new QLineEdit(this);
    findLayout->addWidget(findEdit);
    mainLayout->addLayout(findLayout);
    
    QHBoxLayout *replaceLayout = new QHBoxLayout();
    replaceLayout->addWidget(new QLabel("替换为:"));
    replaceEdit = new QLineEdit(this);
    replaceLayout->addWidget(replaceEdit);
    mainLayout->addLayout(replaceLayout);
    
    caseCheckBox = new QCheckBox("区分大小写", this);
    wholeWordCheckBox = new QCheckBox("全字匹配", this);
    mainLayout->addWidget(caseCheckBox);
    mainLayout->addWidget(wholeWordCheckBox);
    
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    findNextButton = new QPushButton("查找下一个", this);
    replaceButton = new QPushButton("替换", this);
    replaceAllButton = new QPushButton("全部替换", this);
    buttonLayout->addWidget(findNextButton);
    buttonLayout->addWidget(replaceButton);
    buttonLayout->addWidget(replaceAllButton);
    mainLayout->addLayout(buttonLayout);
    
    connect(findNextButton, &QPushButton::clicked, this, &FindReplaceDialog::findNextClicked);
    connect(replaceButton, &QPushButton::clicked, this, &FindReplaceDialog::replaceClicked);
    connect(replaceAllButton, &QPushButton::clicked, this, &FindReplaceDialog::replaceAllClicked);
}

void FindReplaceDialog::findNextClicked() {
    emit findNext(findEdit->text(), 
                 caseCheckBox->isChecked(), 
                 wholeWordCheckBox->isChecked());
}

void FindReplaceDialog::replaceClicked() {
    emit replace(findEdit->text(), 
                replaceEdit->text(), 
                caseCheckBox->isChecked(), 
                wholeWordCheckBox->isChecked());
}

void FindReplaceDialog::replaceAllClicked() {
    emit replaceAll(findEdit->text(), 
                   replaceEdit->text(), 
                   caseCheckBox->isChecked(), 
                   wholeWordCheckBox->isChecked());
}